package com.bigknow.appstore.common.rpc;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class ZipUtil {

    public static boolean isCompress(byte[] data) {
        for (int i = 0; i < RPCConstants.compressHeader.length; i++) {
            if (data[i] != RPCConstants.compressHeader[i]) {
                return false;
            }
        }
        return true;
    }

    public static byte[] compress(byte[] data) {
        ByteArrayOutputStream buf = new ByteArrayOutputStream();
        try {
            GZIPOutputStream out = new GZIPOutputStream(buf);
            out.write(data);
            out.close();
            return buf.toByteArray();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static byte[] uncompress(byte[] data) {
        GZIPInputStream in;
        try {
            in = new GZIPInputStream(new ByteArrayInputStream(data, RPCConstants.compressHeader.length, data.length
                    - RPCConstants.compressHeader.length));
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) != -1) {
                out.write(buf, 0, len);
            }
            return out.toByteArray();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
